package com.training.web.controller;

import com.training.bean.Course;
import com.training.bean.CourseContent;
import com.training.bean.CourseStage;
import com.training.utils.FileUploadUtil;
import com.training.utils.UrlUtils;
import com.training.base.Result;
import com.google.gson.Gson;
import com.training.base.ResponseUtils;
import com.training.web.service.WebCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/web/course")
public class WebCourseController {
    
    @Autowired
    private WebCourseService service;

    @Autowired
    private Gson gson;
    
    @Autowired
    private ResponseUtils responseUtils;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    /**
     * 获取所有课程阶段（后台管理专用）
     * @param request HTTP请求对象
     * @return 课程阶段列表结果
     */
    @GetMapping("/getAllStage")
    public ResponseEntity<Result<List<CourseStage>>> getAllStage(HttpServletRequest request) {
        try {
            List<CourseStage> datas = service.getAllStage();
            if (datas != null){
                // 为每个课程阶段动态构建完整封面URL
                List<CourseStage> stagesWithFullCoverUrls = datas.stream()
                    .map(stage -> {
                        if (stage.getCover() != null && !stage.getCover().isEmpty()) {
                            stage.setCover(UrlUtils.buildFullUrl(request, stage.getCover()));
                        }
                        return stage;
                    })
                    .collect(Collectors.toList());
                return responseUtils.success(stagesWithFullCoverUrls);
            }else {
                return responseUtils.failWithType(500, "获取课程阶段失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return responseUtils.failWithType(500, "获取课程阶段失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加课程阶段（后台管理专用）
     * @param title 阶段标题
     * @param synopsis 阶段简介
     * @param coverFile 阶段封面文件
     * @param request HTTP请求对象
     * @return 添加结果
     */
    @PostMapping("/addStage")
    public ResponseEntity<Result<CourseStage>> addStage(
            @RequestParam("title") String title,
            @RequestParam("synopsis") String synopsis,
            @RequestParam(value = "cover", required = false) MultipartFile coverFile,
            @RequestParam(value = "coverWidth", defaultValue = "0") int coverWidth,
            @RequestParam(value = "coverHeight", defaultValue = "0") int coverHeight,
            HttpServletRequest request) {

        try {
            // 创建课程阶段对象
            CourseStage stage = new CourseStage();
            stage.setTitle(title);
            stage.setSynopsis(synopsis);

            // 处理上传的图片文件
            String fileUrl = null;
            if (coverFile != null && !coverFile.isEmpty()) {
                // 如果指定了尺寸，则进行裁剪
                if (coverWidth > 0 && coverHeight > 0) {
                    fileUrl = fileUploadUtil.uploadAndCropCourseStageCover(coverFile, title, coverWidth, coverHeight);
                } else {
                    fileUrl = fileUploadUtil.uploadCourseStageCover(coverFile, title);
                }
            }
            if (fileUrl != null) {
                stage.setCover(fileUrl);
            }
            stage.setDuration(0);
            // 保存课程阶段
            CourseStage savedStage = service.addStage(stage);
            
            // 动态构建完整封面URL
            if (savedStage.getCover() != null && !savedStage.getCover().isEmpty()) {
                savedStage.setCover(UrlUtils.buildFullUrl(request, savedStage.getCover()));
            }
            
            return responseUtils.success(savedStage);
        } catch (Exception e) {
            return responseUtils.failWithType(500, "添加课程阶段失败: " + e.getMessage());
        }
    }

    /**
     * 更新课程阶段（后台管理专用）
     * @param id 阶段ID
     * @param title 阶段标题
     * @param synopsis 阶段简介
     * @param coverFile 阶段封面文件
     * @param request HTTP请求对象
     * @return 更新结果
     */
    @PostMapping("/updateStage")
    public ResponseEntity<Result<CourseStage>> updateStage(
            @RequestParam("id") int id,
            @RequestParam("title") String title,
            @RequestParam("synopsis") String synopsis,
            @RequestParam(value = "cover", required = false) MultipartFile coverFile,
            @RequestParam(value = "coverWidth", defaultValue = "0") int coverWidth,
            @RequestParam(value = "coverHeight", defaultValue = "0") int coverHeight,
            HttpServletRequest request) {

        try {
            // 先获取现有的阶段对象
            Optional<CourseStage> existingStageOpt = service.findStage(id);
            if (!existingStageOpt.isPresent()) {
                return (ResponseEntity<Result<CourseStage>>) (Object) responseUtils.fail(500, "课程阶段不存在，ID: " + id);
            }

            CourseStage existingStage = existingStageOpt.get();

            // 保存旧封面URL，以便在更新后删除
            String oldCoverUrl = existingStage.getCover();

            // 更新阶段信息
            existingStage.setTitle(title);
            existingStage.setSynopsis(synopsis);

            // 处理上传的新封面文件
            String fileUrl = null;
            if (coverFile != null && !coverFile.isEmpty()) {
                // 如果指定了尺寸，则进行裁剪
                if (coverWidth > 0 && coverHeight > 0) {
                    fileUrl = fileUploadUtil.uploadAndCropCourseStageCover(coverFile, title, coverWidth, coverHeight);
                } else {
                    fileUrl = fileUploadUtil.uploadCourseStageCover(coverFile, title);
                }
            }
            if (fileUrl != null) {
                existingStage.setCover(fileUrl);

                // 如果有旧封面且新旧封面不同，则删除旧封面
                if (oldCoverUrl != null && !oldCoverUrl.isEmpty() && !oldCoverUrl.equals(fileUrl)) {
                    fileUploadUtil.deleteFile(oldCoverUrl);
                }
            }

            // 保存更新后的阶段
            CourseStage updatedStage = service.updateStage(existingStage);

            // 动态构建完整封面URL
            if (updatedStage.getCover() != null && !updatedStage.getCover().isEmpty()) {
                updatedStage.setCover(UrlUtils.buildFullUrl(request, updatedStage.getCover()));
            }

            return responseUtils.success(updatedStage);
        } catch (Exception e) {
            return (ResponseEntity<Result<CourseStage>>) (Object) responseUtils.fail(500, "更新课程阶段失败: " + e.getMessage());
        }
    }

    /**
     * 获取指定阶段的所有课程（后台管理专用）
     * @param csid 课程阶段ID
     * @param request HTTP请求对象
     * @return 课程列表结果
     */
    @GetMapping("/getAllCourse")
    public ResponseEntity<Result<List<Course>>> getAllCourse(@RequestParam int csid, HttpServletRequest request) {
        try {
            List<Course> datas = service.getAllCourse(csid);
            if (datas != null){
                // 为每个课程动态构建完整封面URL
                List<Course> coursesWithFullCoverUrls = datas.stream()
                    .map(course -> {
                        if (course.getCover() != null && !course.getCover().isEmpty()) {
                            course.setCover(UrlUtils.buildFullUrl(request, course.getCover()));
                        }
                        return course;
                    })
                    .collect(Collectors.toList());
                return responseUtils.success(coursesWithFullCoverUrls);
            }else {
                return responseUtils.failWithType(500, "获取课程失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return responseUtils.failWithType(500, "获取课程失败: " + e.getMessage());
        }
    }

    /**
     * 添加课程（后台管理专用）
     * @param csid 课程阶段ID
     * @param title 课程标题
     * @param synopsis 课程简介
     * @param coverFile 课程封面文件
     * @param request HTTP请求对象
     * @return 添加结果
     */
    @PostMapping("/addCourse")
    public ResponseEntity<Result<Course>> addCourse(
            @RequestParam("csid") int csid,
            @RequestParam("title") String title,
            @RequestParam("synopsis") String synopsis,
            @RequestParam(value = "cover", required = false) MultipartFile coverFile,
            @RequestParam(value = "coverWidth", defaultValue = "0") int coverWidth,
            @RequestParam(value = "coverHeight", defaultValue = "0") int coverHeight,
            HttpServletRequest request) {
        
        try {
            // 获取课程阶段标题
            String stageTitle = service.getStageTitleById(csid);
            
            // 创建课程对象
            Course course = new Course();
            course.setCsid(csid);
            course.setTitle(title);
            course.setSynopsis(synopsis);
            
            // 处理上传的图片文件
            String fileUrl = null;
            if (coverFile != null && !coverFile.isEmpty()) {
                // 如果指定了尺寸，则进行裁剪
                if (coverWidth > 0 && coverHeight > 0) {
                    fileUrl = fileUploadUtil.uploadAndCropCourseCover(coverFile, stageTitle, title, coverWidth, coverHeight);
                } else {
                    fileUrl = fileUploadUtil.uploadCourseCover(coverFile, stageTitle, title);
                }
                if (fileUrl != null) {
                    course.setCover(fileUrl);
                }
            }
            course.setDuration(0);
            // 保存课程
            Course savedCourse = service.addCourse(course);
            
            // 动态构建完整封面URL
            if (savedCourse.getCover() != null && !savedCourse.getCover().isEmpty()) {
                savedCourse.setCover(UrlUtils.buildFullUrl(request, savedCourse.getCover()));
            }
            
            return responseUtils.success(savedCourse);
        } catch (Exception e) {
            return responseUtils.failWithType(500, "添加课程失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新课程（后台管理专用）
     * @param id 课程ID
     * @param csid 课程阶段ID
     * @param title 课程标题
     * @param synopsis 课程简介
     * @param coverFile 课程封面文件
     * @param request HTTP请求对象
     * @return 更新结果
     */
    @PostMapping("/updateCourse")
    public ResponseEntity<Result<Course>> updateCourse(
            @RequestParam("id") int id,
            @RequestParam("csid") int csid,
            @RequestParam("title") String title,
            @RequestParam("synopsis") String synopsis,
            @RequestParam(value = "cover", required = false) MultipartFile coverFile,
            @RequestParam(value = "coverWidth", defaultValue = "0") int coverWidth,
            @RequestParam(value = "coverHeight", defaultValue = "0") int coverHeight,
            HttpServletRequest request) {
        
        try {
            // 获取课程阶段标题
            String stageTitle = service.getStageTitleById(csid);
            
            // 先获取现有的课程对象
            Optional<Course> existingCourseOpt = service.findCourse(id);
            if (!existingCourseOpt.isPresent()) {
                return responseUtils.failWithType(500, "课程不存在，ID: " + id);
            }
            
            Course existingCourse = existingCourseOpt.get();
            
            // 保存旧封面URL，以便在更新后删除
            String oldCoverUrl = existingCourse.getCover();
            
            // 更新课程信息
            existingCourse.setCsid(csid);
            existingCourse.setTitle(title);
            existingCourse.setSynopsis(synopsis);
            
            // 处理上传的新封面文件
            String fileUrl = null;
            if (coverFile != null && !coverFile.isEmpty()) {
                // 如果指定了尺寸，则进行裁剪
                if (coverWidth > 0 && coverHeight > 0) {
                    fileUrl = fileUploadUtil.uploadAndCropCourseCover(coverFile, stageTitle, title, coverWidth, coverHeight);
                } else {
                    fileUrl = fileUploadUtil.uploadCourseCover(coverFile, stageTitle, title);
                }
                if (fileUrl != null) {
                    existingCourse.setCover(fileUrl);
                }
            }
            
            // 保存更新后的课程
            Course updatedCourse = service.updateCourse(existingCourse);
            
            // 如果上传了新封面且旧封面存在，则删除旧封面文件
            if (fileUrl != null && oldCoverUrl != null && !oldCoverUrl.isEmpty() && !oldCoverUrl.equals(fileUrl)) {
                fileUploadUtil.deleteFile(oldCoverUrl);
            }
            
            // 动态构建完整封面URL
            if (updatedCourse.getCover() != null && !updatedCourse.getCover().isEmpty()) {
                updatedCourse.setCover(UrlUtils.buildFullUrl(request, updatedCourse.getCover()));
            }
            
            return responseUtils.success(updatedCourse);
        } catch (Exception e) {
            return (ResponseEntity<Result<Course>>) (Object) responseUtils.fail(500, "更新课程失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取指定课程的所有内容（后台管理专用）
     * @param cid 课程ID
     * @param request HTTP请求对象
     * @return 课程内容列表结果
     */
    @GetMapping("/getAllCourseContent")
    public ResponseEntity<Result<List<CourseContent>>> getAllCourseContent(@RequestParam int cid, HttpServletRequest request) {
        try {
            List<CourseContent> datas = service.getAllCourseContent(cid);
            if (datas != null){
                // 为每个课程内容动态构建完整封面URL
                List<CourseContent> contentsWithFullCoverUrls = datas.stream()
                    .map(content -> {
                        if (content.getCover() != null && !content.getCover().isEmpty()) {
                            content.setCover(UrlUtils.buildFullUrl(request, content.getCover()));
                        }
                        return content;
                    })
                    .collect(Collectors.toList());
                return responseUtils.success(contentsWithFullCoverUrls);
            }else {
                return responseUtils.failWithType(500, "获取课程内容失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return responseUtils.failWithType(500, "获取课程内容失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加课程内容（后台管理专用）
     * @param cid 课程ID
     * @param title 内容标题
     * @param content 内容正文
     * @param coverFile 内容封面文件
     * @param request HTTP请求对象
     * @return 添加结果
     */
    @PostMapping("/addContent")
    public ResponseEntity<Result<CourseContent>> addContent(
            @RequestParam("cid") int cid,
            @RequestParam("title") String title,
            @RequestParam("content") String content,
            @RequestParam(value = "cover", required = false) MultipartFile coverFile,
            HttpServletRequest request) {
        
        try {
            // 获取课程标题和阶段标题
            String courseTitle = service.getCourseTitleById(cid);
            Optional<Course> courseOpt = service.findCourse(cid);
            String stageTitle = "unknown";
            if (courseOpt.isPresent()) {
                int csid = courseOpt.get().getCsid();
                stageTitle = service.getStageTitleById(csid);
            }
            
            // 创建内容对象
            CourseContent contentObj = new CourseContent();
            contentObj.setCid(cid);
            contentObj.setTitle(title);
            contentObj.setContent(content);
            
            // 处理上传的图片文件
            String fileUrl = null;
            if (coverFile != null && !coverFile.isEmpty()) {
                fileUrl = fileUploadUtil.uploadCourseContentCover(coverFile, stageTitle, courseTitle, title);
                if (fileUrl != null) {
                    contentObj.setCover(fileUrl);
                }
            }
            contentObj.setDuration(0);
            // 保存内容
            CourseContent savedContent = service.addContent(contentObj);
            
            // 动态构建完整封面URL
            if (savedContent.getCover() != null && !savedContent.getCover().isEmpty()) {
                savedContent.setCover(UrlUtils.buildFullUrl(request, savedContent.getCover()));
            }
            
            return responseUtils.success(savedContent);
        } catch (Exception e) {
            return responseUtils.failWithType(500, "添加课程内容失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新课程内容（后台管理专用）
     * @param id 内容ID
     * @param cid 课程ID
     * @param title 内容标题
     * @param content 内容正文
     * @param coverFile 内容封面文件
     * @param request HTTP请求对象
     * @return 更新结果
     */
    @PostMapping("/updateContent")
    public ResponseEntity<Result<CourseContent>> updateContent(
            @RequestParam("id") int id,
            @RequestParam("cid") int cid,
            @RequestParam("title") String title,
            @RequestParam("content") String content,
            @RequestParam(value = "cover", required = false) MultipartFile coverFile,
            @RequestParam(value = "coverWidth", defaultValue = "0") int coverWidth,
            @RequestParam(value = "coverHeight", defaultValue = "0") int coverHeight,
            HttpServletRequest request) {
        
        try {
            // 先获取现有的内容对象
            Optional<CourseContent> existingContentOpt = service.findContent(id);
            if (!existingContentOpt.isPresent()) {
                return (ResponseEntity<Result<CourseContent>>) (Object) responseUtils.fail(500, "内容不存在，ID: " + id);
            }
            
            CourseContent existingContent = existingContentOpt.get();
            
            // 保存旧封面URL，以便在更新后删除
            String oldCoverUrl = existingContent.getCover();
            
            // 获取课程标题和阶段标题
            String courseTitle = service.getCourseTitleById(cid);
            Optional<Course> courseOpt = service.findCourse(cid);
            String stageTitle = "unknown";
            if (courseOpt.isPresent()) {
                int csid = courseOpt.get().getCsid();
                stageTitle = service.getStageTitleById(csid);
            }
            
            // 更新内容信息
            existingContent.setCid(cid);
            existingContent.setTitle(title);
            existingContent.setContent(content);
            
            // 处理上传的新封面文件
            String fileUrl = null;
            if (coverFile != null && !coverFile.isEmpty()) {
                // 如果指定了尺寸，则进行裁剪
                if (coverWidth > 0 && coverHeight > 0) {
                    fileUrl = fileUploadUtil.uploadAndCropCourseContentCover(coverFile, stageTitle, courseTitle, title, coverWidth, coverHeight);
                } else {
                    fileUrl = fileUploadUtil.uploadCourseContentCover(coverFile, stageTitle, courseTitle, title);
                }
                if (fileUrl != null) {
                    existingContent.setCover(fileUrl);
                }
            }
            
            // 保存更新后的内容
            CourseContent updatedContent = service.updateContent(existingContent);
            
            // 如果上传了新封面且旧封面存在，则删除旧封面文件
            if (fileUrl != null && oldCoverUrl != null && !oldCoverUrl.isEmpty() && !oldCoverUrl.equals(fileUrl)) {
                fileUploadUtil.deleteFile(oldCoverUrl);
            }
            
            // 动态构建完整封面URL
            if (updatedContent.getCover() != null && !updatedContent.getCover().isEmpty()) {
                updatedContent.setCover(UrlUtils.buildFullUrl(request, updatedContent.getCover()));
            }
            
            return responseUtils.success(updatedContent);
        } catch (Exception e) {
            return (ResponseEntity<Result<CourseContent>>) (Object) responseUtils.fail(500, "更新内容失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除课程内容（后台管理专用）
     * @param id 内容ID
     * @return 删除结果
     */
    @DeleteMapping("/deleteContent/{id}")
    public ResponseEntity<Result<Object>> deleteContent(@PathVariable int id) {
        try {
            // 先获取要删除的内容对象
            Optional<CourseContent> contentOpt = service.findContent(id);
            if (!contentOpt.isPresent()) {
                return responseUtils.fail(500, "课程内容不存在，ID: " + id);
            }
            
            CourseContent content = contentOpt.get();
            
            // 删除文件系统中的图片文件（如果存在）
            if (content.getCover() != null && !content.getCover().isEmpty()) {
                fileUploadUtil.deleteFile(content.getCover());
            }
            
            // 从数据库中删除内容
            service.deleteContent(id);
            
            return responseUtils.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            return responseUtils.fail(500, "删除课程内容失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除课程（后台管理专用）
     * @param id 课程ID
     * @return 删除结果
     */
    @DeleteMapping("/deleteCourse/{id}")
    public ResponseEntity<Result<Object>> deleteCourse(@PathVariable int id) {
        try {
            // 先获取要删除的课程对象
            Optional<Course> courseOpt = service.findCourse(id);
            if (!courseOpt.isPresent()) {
                return responseUtils.fail(500, "课程节选不存在，ID: " + id);
            }
            
            Course course = courseOpt.get();
            
            // 删除该课程下的所有内容及其文件
            List<CourseContent> contents = service.getAllCourseContent(id);
            for (CourseContent content : contents) {
                // 删除内容的图片文件（如果存在）
                if (content.getCover() != null && !content.getCover().isEmpty()) {
                    fileUploadUtil.deleteFile(content.getCover());
                }
                
                // 从数据库中删除内容
                service.deleteContent(content.getId());
            }
            
            // 删除课程节选的封面文件（如果存在）
            if (course.getCover() != null && !course.getCover().isEmpty()) {
                fileUploadUtil.deleteFile(course.getCover());
            }
            
            // 从数据库中删除课程节选
            service.deleteCourse(id);
            
            // 修复：明确指定Result的类型参数为Object
            return responseUtils.success(null, "课程节选删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return responseUtils.fail(500, "删除课程节选失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除课程阶段（后台管理专用）
     * @param id 阶段ID
     * @return 删除结果
     */
    @DeleteMapping("/deleteStage/{id}")
    public ResponseEntity<Result<Object>> deleteStage(@PathVariable int id) {
        try {
            // 先获取要删除的课程阶段对象
            Optional<CourseStage> stageOpt = service.findStage(id);
            if (!stageOpt.isPresent()) {
                return responseUtils.fail(500, "课程阶段不存在，ID: " + id);
            }
            
            CourseStage stage = stageOpt.get();
            
            // 删除该阶段下的所有课程节选及其内容和文件
            List<Course> courses = service.getAllCourse(id);
            for (Course course : courses) {
                // 删除该课程下的所有内容及其文件
                List<CourseContent> contents = service.getAllCourseContent(course.getId());
                for (CourseContent content : contents) {
                    // 删除内容的图片文件（如果存在）
                    if (content.getCover() != null && !content.getCover().isEmpty()) {
                        fileUploadUtil.deleteFile(content.getCover());
                    }
                    
                    // 从数据库中删除内容
                    service.deleteContent(content.getId());
                }
                
                // 删除课程节选的封面文件（如果存在）
                if (course.getCover() != null && !course.getCover().isEmpty()) {
                    fileUploadUtil.deleteFile(course.getCover());
                }
                
                // 从数据库中删除课程节选
                service.deleteCourse(course.getId());
            }
            
            // 删除课程阶段的封面文件（如果存在）
            if (stage.getCover() != null && !stage.getCover().isEmpty()) {
                fileUploadUtil.deleteFile(stage.getCover());
            }
            
            // 从数据库中删除课程阶段
            service.deleteStage(id);
            
            return responseUtils.success(null, "课程阶段删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return responseUtils.fail(500, "删除课程阶段失败: " + e.getMessage());
        }
    }
    
}